package com.blog.controller;

import com.blog.exception.ExceptionEnum;
import com.blog.exception.MyException;
import com.blog.pojo.PageBean;
import com.blog.pojo.ResultResponse;
import com.blog.pojo.User;
import com.blog.pojo.UserInfoVO;
import com.blog.service.UserService;
import com.blog.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //注册
    @PostMapping("/register")
    public ResultResponse register(@RequestBody User user) {
        return userService.register(user);
    }

    //登录
    @PostMapping("/login")
    public ResultResponse login(@RequestBody User user) {
        UserInfoVO loginUser = userService.login(user);
        //判断：登录用户是否存在且有效
        if (loginUser != null) {
            if(loginUser.getValid() == 0){
                throw new MyException(ExceptionEnum.INVALID_ACCOUNT);
            }
            //自定义信息
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            claims.put("email", loginUser.getEmail());
            claims.put("image", loginUser.getImage());
            claims.put("identity", loginUser.getIdentity());

            //使用JWT工具类，生成身份令牌
            String token = JwtUtils.generateJwt(claims);
            return ResultResponse.success(token);
        }
        throw new MyException(ExceptionEnum.ERROR_EMAIL_OR_PASSWORD);
    }

    //查看其他用户信息（单个）
    @GetMapping("/users/{id}")
    public ResultResponse getUserById(@PathVariable Integer id){
        UserInfoVO userInfo = userService.getUserById(id);
        return ResultResponse.success(userInfo);
    }

    //冻结用户
    @PutMapping("/users/freeze/{id}")
    public ResultResponse freezeUser(@PathVariable Integer id){
        userService.freezeUser(id);
        return ResultResponse.success();
    }

    //解封用户
    @PutMapping("/users/revert/{id}")
    public ResultResponse revertUser(@PathVariable Integer id){
        userService.revertUser(id);
        return ResultResponse.success();
    }

    //获取当前用户
    @GetMapping("/currentUser/info")
    public ResultResponse getCurrentUser() {
        UserInfoVO userInfo = userService.getCurrentUser();
        return ResultResponse.success(userInfo);
    }

    //修改用户信息
    @PutMapping("/currentUser/update")
    public ResultResponse updateUser(@RequestParam(value = "username", required = false) String username,
                             @RequestPart(value = "image", required = false) MultipartFile image) throws IOException {
        if((image == null || image.isEmpty()) && (username == null || username.isEmpty())){
            throw new MyException(ExceptionEnum.NOT_MODIFIED);
        }
        return ResultResponse.success(userService.updateUser(username, image));
    }

    //登陆后修改密码
    @PutMapping("/currentUser/password")
    public ResultResponse updatePassword(@RequestParam(value = "oldPassword") String oldPassword,
                                        @RequestParam(value = "newPassword") String newPassword){
        if((oldPassword == null || oldPassword.isEmpty()) || (newPassword == null || newPassword.isEmpty())){
            throw new MyException(ExceptionEnum.EMPTY_PASSWORD);
        }
        return userService.updatePassword(oldPassword, newPassword);
    }

    //登陆页面，忘记密码修改密码
    @PutMapping("/login/password")
    public ResultResponse changePassword(@RequestParam(value = "email") String email,
                                         @RequestParam(value = "password") String newPassword){
        if(newPassword == null || newPassword.isEmpty()){
            throw new MyException(ExceptionEnum.EMPTY_PASSWORD);
        }
        userService.changePassword(email, newPassword);
        return ResultResponse.success();
    }

    //分页查询普通用户
    @GetMapping("/users")
    public ResultResponse listUsers(@RequestParam(defaultValue = "1") Integer page) {
        //分页查询
        Integer pageSize = 10;
        PageBean pageBean = userService.listUsers(page, pageSize);
        return ResultResponse.success(pageBean);
    }

    //带条件查询普通用户
    @GetMapping("/users/search")
    public ResultResponse listUsersByCondition(@RequestParam(defaultValue = "1") Integer page, @RequestParam String condition){
        if(condition == null || condition.isEmpty()){
            throw new MyException(ExceptionEnum.EMPTY_CONDITION);
        }
        Integer pageSize = 10;
        PageBean pageBean = userService.listUsersByCondition(page, pageSize, condition);
        return ResultResponse.success(pageBean);
    }

}